package xml;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import android.os.Environment;

/**
 * 
 * Contiene metodi e costanti di utilit� per le classi del package xml
 * 
 */
public class NodeUtilities {

	private String nodeName;
	
	public static final String defaultPlaylistLocation=Environment
			.getExternalStorageDirectory().getAbsolutePath();
	
	public static final String defaultPlaylist = defaultPlaylistLocation+"/"+
			"Playlists.xml";
	public static final String nodeNameImage = "image";
	public static final String nodeNamePlaylist = "playlist";
	public static final String attributeName = "path";

	public NodeUtilities() {
		super();
	}

	/**
	 * 
	 * @param nodeName
	 */
	public void setNodeName(String nodeName) {
		this.nodeName = nodeName;
	}

	/**
	 * 
	 * @return nodeName
	 */
	public String getNodeName() {
		return nodeName;
	}

	/**
	 * 
	 * @param filename
	 * @return ritorna un document dato il file in ingresso
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws IOException
	 */
	public static Document getDocument(String filename)
			throws ParserConfigurationException, SAXException, IOException {

		DocumentBuilderFactory documentFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder builder = documentFactory.newDocumentBuilder();
		Document document = builder.parse(new File(filename));
		return document;
	}

	/**
	 * 
	 * Salva un document in un file specificato da filename
	 * 
	 * @param filename
	 * @param document
	 * @throws TransformerFactoryConfigurationError
	 * @throws TransformerConfigurationException
	 * @throws TransformerException
	 */
	public static void saveDocument(String filename, Document document)
			throws TransformerFactoryConfigurationError,
			TransformerConfigurationException, TransformerException {

		TransformerFactory transformerFactory = TransformerFactory
				.newInstance();
		Transformer transformer = transformerFactory.newTransformer();

		transformer.setOutputProperty(OutputKeys.METHOD, "xml");
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		
		DOMSource source = new DOMSource(document);
		StreamResult result = new StreamResult(new File(filename));

		transformer.transform(source, result);
	}

}